package produce_consume;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @date 2020/3/9 23:37
 */
public class Code03_SimplePC3 {
    private AtomicInteger counter = new AtomicInteger(0);
    private BlockingQueue<Integer> taskQueue;
    private static final int DEFAULT_CAPACITY = 10;
    public Code03_SimplePC3() {
        this(DEFAULT_CAPACITY);
    }

    public Code03_SimplePC3(int capacity) {
        taskQueue = new ArrayBlockingQueue<>(capacity);
    }

    public void produce() throws InterruptedException {
        while (true) {
            System.out.println(Thread.currentThread().getName() + "生产了:" + (counter.incrementAndGet()));
            taskQueue.put(counter.get());
            Thread.sleep(20);
        }
    }

    public void consume() throws InterruptedException {
        while (true) {
            System.out.println(Thread.currentThread().getName() + "消费了:" + (taskQueue.take()));
            Thread.sleep(2000);
        }

    }

    public static void main(String[] args) throws InterruptedException {
        Code03_SimplePC3 pc = new Code03_SimplePC3();
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                try {
                    pc.produce();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "P" + i).start();

            new Thread(() -> {
                try {
                    pc.consume();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "C" + i).start();
        }

    }
}
